from flask import Flask, url_for, render_template, request , Response, redirect
import pymysql
import decimal
import sys
import string
import datetime
import json
import platform
import pymysql.cursors
from flask_cors import CORS



class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        
        return json.JSONEncoder.default(self,obj)

app = Flask(__name__)
CORS(app, supports_credentials=True)

cursorclass = pymysql.cursors.DictCursor  #返回的数据是字典类型 而不是元祖



def transferContent(self, content):
    if content is None:
        return None
    else:
        string = ""
        for c in content:
            if c == '"':
                string += '\\\"'
            elif c == "'":
                string += "\\\'"
            elif c == "\\":
                string += "\\\\"
            else:
                string += c
        return string
def SendSQL(sql):
    
    conn = pymysql.connect(
        host='virtualman.top',
        port=3306,
        user='yy_garden',
        passwd='yy_garden_key',
        db='yy_breakfast',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor,
    )
    cursor = conn.cursor()
    cursor.execute(sql)
    results = cursor.fetchall()  # 接受返回结果行
    # for row in results:
    cursor.close()
    conn.close()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    return results

@app.route('/index')
@app.route('/',methods=['GET'])
def index():
    return "helloworld!"
    # **locals()

@app.route('/api/GetAllFoods')
def GetAllFoods():
    
    sql = 'SELECT * FROM `yy_breakfast`.`foods`'

    res_date=[]
    res_date = SendSQL(sql)
    return json.dumps(res_date,cls=DateEncoder)

@app.route('/api/GetNewBaseInfo')
def GetNewBaseInfo():
    sql = 'SELECT * FROM `yy_breakfast`.`base_infos` ORDER BY `id` DESC LIMIT 1'
    res_date = SendSQL(sql)
    print(res_date)
    return json.dumps(res_date,cls=DateEncoder)

@app.route('/api/GetOrdersByReceiverId')
def GetOrdersByReceiverId():
    receiver_id = request.args.get('receiver_id')
    sql = "SELECT * FROM `yy_breakfast`.`breakfast_orders` WHERE `receiver_id` = '"+receiver_id+"' LIMIT 0,1000"
    res_date = SendSQL(sql)
    
    return json.dumps(res_date,cls=DateEncoder)
    #SELECT * FROM `yy_breakfast`.`breakfast_orders` WHERE `receiver_id` = '1' LIMIT 0,1000

@app.route('/api/GetAllOrderList') 
def GetAllOrderList():
    sql = "SELECT * FROM `yy_breakfast`.`breakfast_orders`"
    res_date = SendSQL(sql)
    
    return json.dumps(res_date,cls=DateEncoder)

sysstr = platform.system()
if (sysstr == "Windows"):
    app.debug=True
elif (sysstr == "Linux"):
    app.debug=False
if(app.debug==True):
    app.run('192.168.1.5')
else:
    app.run('0.0.0.0', port=80)